(function(){
  app = angular.module('app', []);

  function fn($scope, $http){
    $scope.init = false
    $scope.userInfo = null;
    var pwdInfo = {"password_trade" : "*BAN*FBt*E3*E9*C4*D1*03*1D*D4*1F*C6*FC*BDbG*97*883*91G*16bw*22*A05*A8*CCL8G*97*883*91G*16bw*22*A05*A8*CCL8G*97*883*91G*16bw*22*A05*A8*CCL8*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00*00", "mac" : "mac", "disknum" : "disknum"};
    $scope.request = {
      method : '请选择HTTP请求类型',
      data : JSON.stringify(pwdInfo, null, 4)
    };

    $scope.methodList = ['GET', 'POST'];

    

    var userSessionCbf = function(err, res){
      $scope.init = true;
      if(err){
        $scope.userInfo = null;
      }else{
        if(res.anonymous === false){
          $scope.userInfo = res;
        }else{
          $scope.userInfo = null;
        }
      }
    };

    $http.get('/user/session').success(function(res){
      userSessionCbf(null, res);
    }).error(userSessionCbf);



    $scope.logout = function(){
      $http.delete('/user/session').success(function(res){
        userSessionCbf(null, res);
      }).error(userSessionCbf);
    };

    $scope.send = function(){

      var method = $scope.request.method;
      var url = $scope.request.url;
      if(!url || !method || method == '请选择HTTP请求类型'){
        $scope.error = 'url和请求类型均不能为空！';
        return;
      }
      if(url.indexOf('/rest') == 0){
        url = url.substring(5);
      }
      var promise = null;
      if(method == 'GET'){
        promise = $http.get(url);
      }else{
        try{
          var postData = JSON.parse($scope.request.data || '{}');
        }catch(err){
          $scope.error = err.toString();
          return;
        }
        promise = $http.post(url, postData);
      }
      promise.success(function(res, statusCode){
          var result = {
            '结果' : '成功',
            '状态码' : statusCode,
            '返回数据' : res
          };
          $scope.request.result = JSON.stringify(result, null, 2);
        }).error(function(err, statusCode){
          var result = {
            '结果' : '失败',
            '状态码' : statusCode,
            '返回数据' : err
          };
          $scope.request.result = JSON.stringify(result, null, 2);
        });
    };

    $scope.$watch('request', function(){
      $scope.error = '';
    }, true);

  }

  app.controller('AppController', fn);



})();
